<?php

namespace Johnm\Probackend\Controllers;

use Input;
use View;
use Lang;
use Cartalyst\Sentry\Groups\Eloquent\Provider as Group;
use Illuminate\Support\Facades\Validator;
use Johnm\Probackend\Datatable\Facades\DatatableFacade as Datatable;
use Illuminate\Support\Collection;

class AdministratorGroupController extends CoreController {

    private $groups;

    public function __construct(Group $groups) {
        $this->groups = $groups;
    }

    /**
     * Get validation rule for update/storge administrator group
     * 
     * @param integer $id
     * @return array
     */
    private function rules($id = null) {
        return [
            'name' => "required|max:255|regex:/[a-z_]+/|unique:groups,name" . ($id == null ? "" : ",$id"),
            'title' => "required|max:255",
        ];
    }

    /**
     * Show the api for datatable get data of administrator group
     * 
     * @return json string
     */
    public function datatable() {
        $groups = $this->groups->findAll();
        return Datatable::collection(new Collection($groups))
                        ->showColumns('id', 'title', 'name')
                        ->searchColumns('name', 'title')
                        ->orderColumns('id', 'name', 'title')
                        ->make();
    }

    /**
     * Display a listing of the administrator group.
     *
     * @return Response
     */
    public function index() {
        $this->layout->content = View::make('probackend::administrator_group.index');
    }

    /**
     * Show the form for creating a new administrator group.
     *
     * @return Response
     */
    public function create() {
        return View::make('probackend::administrator_group.create');
    }

    /**
     * Store a newly created administrator group in storage.
     *
     * @return Response
     */
    public function store() {
        // get all input data
        $data = Input::all();

        // create validator for validate input data
        $validator = Validator::make($data, $this->rules(), Lang::get("probackend::administrator_group_validator"));

        // validate data
        if ($validator->fails()) {
            // Input data have errors. Response to client
            return json_encode([
                'success' => 0,
                'title' => Lang::get("probackend::administrator_group.message_storge_error_title"),
                'messages' => $validator->messages()->all()
            ]);
        } else {
            // Input data haven't validate error
            $group = $this->groups->create(array(
                'name' => $data['name'],
                'title' => ucfirst($data['title']),
                'permissions' => isset($data['permissions']) ? $data['permissions'] : array(),
            ));
            return json_encode([
                'success' => 1,
                'title' => Lang::get("probackend::administrator_group.message_storge_success_title"),
                'messages' => [Lang::get("probackend::administrator_group.message_storge_success")]
            ]);
        }
    }

    /**
     * Display the specified administrator group.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id) {
        $group = $this->groups->findById($id);
        return View::make("probackend::administrator_group.show", $group->toArray());
    }

    /**
     * Show the form for editing the specified administrator group.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id) {
        $group = $this->groups->findById($id);
        return View::make("probackend::administrator_group.edit", $group->toArray());
    }

    /**
     * Update the specified administrator group in storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function update($id) {
        $data = Input::all();
        $validator = Validator::make($data, $this->rules($id), Lang::get("probackend::administrator_group_validator"));
        if ($validator->fails()) {
            return json_encode([
                'success' => 0,
                'title' => Lang::get("probackend::administrator_group.message_update_error_title"),
                'messages' => $validator->messages()->all(),
            ]);
        } else {
            $group = $this->groups->findById($id);
            $group->name = $data['name'];
            $group->title = $data['title'];

            $reset_permistions = array();
            foreach ($group->permissions as $key => $value) {
                $reset_permistions[$key] = 0;
            }

            // Update the permissions
            if (isset($data['permissions'])) {
                $group->permissions = array_merge($reset_permistions, $data['permissions']);
            } else {
                $group->permissions = $reset_permistions;
            }

            if ($group->save()) {
                return json_encode([
                    'success' => 1,
                    'title' => Lang::get("probackend::administrator_group.message_update_success_title"),
                    'messages' => [Lang::get("probackend::administrator_group.message_update_success")]
                ]);
            } else {
                return json_encode([
                    'success' => 0,
                    'title' => Lang::get("probackend::administrator_group.message_update_error_title"),
                    'messages' => [Lang::get("probackend::administrator_group.message_update_error")],
                ]);
            }
        }
    }

    /**
     * Remove the specified administrator group from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id) {
        $group = $this->groups->findById($id);
        $title = $group->title;
        if ($group->delete()) {
            return json_encode([
                'success' => 1,
                'title' => Lang::get("probackend::administrator_group.message_delete_success_title"),
                'messages' => [Lang::get("probackend::administrator_group.message_delete_success")]
            ]);
        } else {
            return json_encode([
                'success' => 0,
                'title' => Lang::get("probackend::administrator_group.message_delete_error_title"),
                'messages' => [Lang::get("probackend::administrator_group.message_delete_error")],
            ]);
        }
    }

}
